<template>
  <div>
    <!-- 搜索栏 -->
    <el-form v-show="showSearch" :inline="true" :model="queryParams">
      <el-form-item label="名称:">
        <el-input v-model="queryParams.name" clearable placeholder="请输入课程名"
                  style="width: 150px" @input="handleQuery"/>
      </el-form-item>
      <el-form-item label="任课教师:">
        <el-input v-model="queryParams.teacherName" clearable placeholder="请输入任课教师"
                  style="width: 150px" @input="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <svg-icon icon-file-name="white-search" style="color: #1abc9c"></svg-icon>
          搜索
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <el-row :gutter="10" style="margin-bottom: 15px">
      <el-col :span="1.5">
        <el-button :disabled="enrollmentIdList.length === 0" icon="Delete" plain type="danger"
                   @click="handleBatchEndEnrollment">批量结课
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-plus" plain type="primary" @click="prepareNewEntry">
          新增课堂
        </el-button>
      </el-col>
      <refresh-and-hide @refresh="handleRefresh" @toggle-search="handleToggleSearch"/>
    </el-row>
    <div class="scroll-container">
      <!-- 表格展示 -->
      <el-table v-loading="loading" :data="enrollmentList" border @sort-change="handleSortChange"
                @selection-change="handleSelectionChange">
        <!-- 表格选择列 -->
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <el-table-column align="center" label="ID" prop="enrollmentId" width="55"></el-table-column>
        <!--缩略图-->
        <el-table-column align="center" label="课程封面" prop="courseImage" width="155">
          <template #default="scope">
            <el-image :lazy="true" :src="scope.row.courseImage" class="image-cover" fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <!-- 课程名 -->
        <el-table-column align="center" label="课程名" prop="name">
        </el-table-column>
        <!-- 授课的教师 -->
        <el-table-column align="center" label="任课教师" prop="teacherName" ></el-table-column>
        <el-table-column align="center" label="容量" prop="maxNum" width="90"></el-table-column>
        <el-table-column align="center" label="已选人数" prop="presentNum" width="100"></el-table-column>
        <el-table-column align="center" label="授课年级" prop="grade" sortable="custom" width="100">
          <template #default="scope">
            {{ ['大一', '大二', '大三', '大四'][scope.row.grade - 1] }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="上课时间" prop="upClassTime" sortable width="130">
          <template #default="scope">
            <div class="time">
              <span style="margin-left: 10px">{{formatClassTime(scope.row.week, scope.row.onClass)}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="学分限制" prop="upClassTime" sortable width="100">
          <template #default="scope">
            <div class="time">
              <span style="margin-left: 10px">{{formatCreditsLimit(scope.row.minCredits, scope.row.maxCredits)}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="课堂状态" prop="status">
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="选课状态" prop="status">
          <template #default="scope">
            {{ formatSelectStatus(scope.row.selectStatus) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="课堂结课" prop="endTime" sortable width="130">
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.endTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="选课截止" prop="stopTime" sortable >
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.stopTime }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column align="center" label="操作" width="220">
          <template #default="scope">
            <el-button class="sdf" link type="primary" @click="handleEdit(scope.row)">
              <svg-icon icon-file-name="edit"></svg-icon>
              编辑
            </el-button>
            <el-button class="sd" link type="danger" @click="handleEndCourse(scope.row.enrollmentId)">
              <svg-icon icon-file-name="delete"></svg-icon>
              结课
            </el-button>
            <el-button class="sdf" link type="primary" @click="handleStopSelectCourse(scope.row.enrollmentId)">
              <svg-icon icon-file-name="edit"></svg-icon>
              结束选课
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <pagination v-if="total > 0" :limit="pagInfo.pageSize" :page="pagInfo.currentPage" :total="total"
                style="float: right;" @pagination="getCoursesList"
                @update_limit="pagInfo.pageSize = $event"
                @update_page="pagInfo.currentPage = $event"/>
    <el-dialog :visible.sync="studentCourseDialogVisible" :title="GTitle" width="50%">
      <el-form :model="selectCourseForm" ref="selectCourseFormRef" :rules="rules">
        <el-form-item :label-width="formLabelWidth" label="选择课程:" prop="courseId">
          <el-select v-model="selectCourseForm.courseId" placeholder="请选择课程">
            <el-option v-for="item in courseIdWithNameList" :key="item.courseId" :label="item.courseName" :value="item.courseId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="选择教师:" prop="teacherId">
          <el-select v-model="selectCourseForm.teacherId" placeholder="请选择老师">
            <el-option v-for="item in teacherIdWithNameList" :key="item.teacherId" :label="item.teacherName" :value="item.teacherId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="课程容量:" prop="maxNum">
          <el-input v-model="selectCourseForm.maxNum" type="number" placeholder="课程容量" style="width: 100px; display: inline-block;"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="上课时间" prop="week">
          <el-select v-model="selectCourseForm.week" placeholder="请选择上课时间">
            <el-option label="星期一" :value="1"></el-option>
            <el-option label="星期二" :value="2"></el-option>
            <el-option label="星期三" :value="3"></el-option>
            <el-option label="星期四" :value="4"></el-option>
            <el-option label="星期五" :value="5"></el-option>
            <el-option label="星期六" :value="6"></el-option>
            <el-option label="星期日" :value="7"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="课程节数(第几节课上课):" prop="onClass">
          <el-select v-model="selectCourseForm.onClass" placeholder="请选择上课时间">
            <el-option label="第一节课" :value="1"></el-option>
            <el-option label="第二节课" :value="2"></el-option>
            <el-option label="第三节课" :value="3"></el-option>
            <el-option label="第四节课" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="此次课程的学生年级:" prop="grade">
          <el-select v-model="selectCourseForm.grade" placeholder="请选择学生年级">
            <el-option label="大一" :value="1"></el-option>
            <el-option label="大二" :value="2"></el-option>
            <el-option label="大三" :value="3"></el-option>
            <el-option label="大四" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="学分限制:">
          <div>
            <el-input v-model="selectCourseForm.minCredits" type="number" placeholder="最低学分" style="width: 100px; display: inline-block;"></el-input>
            <span style="display: inline-block; margin: 0 10px;">至</span>
            <el-input v-model="selectCourseForm.maxCredits" type="number" placeholder="最高学分" style="width: 100px; display: inline-block;"></el-input>
          </div>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="该次课堂结课时间:" prop="endTime">
          <el-date-picker
            v-model="selectCourseForm.endTime"
            type="date"
            placeholder="选择日期"
            format="yyyy/MM/dd"
            value-format="yyyy/MM/dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="该次选课结束时间:" prop="stopTime">
          <el-date-picker
            v-model="selectCourseForm.stopTime"
            type="date"
            placeholder="选择日期"
            format="yyyy/MM/dd"
            value-format="yyyy/MM/dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否自动为符合条件的学生加入课堂" prop="ifPrimary" v-if="!isEditing">
          <el-switch v-model="selectCourseForm.isAutoAdd"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="studentCourseDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="saveSelectCourse">保存</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import refreshAndHide from "@/common/refreshAndHide.vue";
import Pagination from "@/common/pagination.vue";
import {
  getEnrollment,
  adminEndCurse,
  getTeacherIdWithName,
  getCourseIdWithName,
  updateSelectCourse, addSelectCourse,endEnrollmentOnList,adminStopSelectCourse
} from "@/apis/admin";

export default {
  // 组件注册，允许在模板中使用导入的组件
  components: {
    Pagination, // 分页组件
    refreshAndHide // 刷新和隐藏组件
  },
  computed:{
    GTitle() {
      return this.isEditing ? '编辑课堂' : '新增课堂'
    }
  },
  // 组件的响应数据对象
  data() {
    return {
      rules: {
        courseId: [
          { required: true, message: '请选择课程', trigger: 'change' }
        ],
        teacherId: [
          { required: true, message: '请选择老师', trigger: 'change' }
        ],
        maxNum: [
          { required: true, message: '请输入课程容量', trigger: 'change' },
        ],
        week: [
          { required: true, message: '请选择上课时间', trigger: 'change' }
        ],
        onClass: [
          { required: true, message: '请选择上课时间', trigger: 'change' }
        ],
        grade: [
          { required: true, message: '请选择学生年级', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择该次课程结课时间', trigger: 'change' }
        ],
        stopTime: [
          { required: true, message: '请选择该次选课结束时间', trigger: 'change' }
        ]
      },
      teacherIdWithNameList: [], // 教师id对应的教师名
      courseIdWithNameList: [], // 课程id对应的课程名

      // 控制搜索表单显示的布尔值
      showSearch: true,
      // 搜索参数对象
      queryParams: {
        name: '', // 课程名
        teacherName: '' // 任课教师
      },
      //分页信息
      pagInfo: {
        currentPage: 1,
        pageSize: 10
      },
      // 存储选中的选课列表
      enrollmentIdList: [],
      // 存储选课列表的数组
      enrollmentList: [],
      // 控制表格加载状态的布尔值
      loading: false,
      // 存储总信息数量的变量
      total: 0,

      isEditing: false, // 控制是否是编辑状态
      studentCourseDialogVisible: false, // 控制编辑对话框的显示
      selectCourseForm: { // 编辑学生课程表单的数据模型
        enrollmentId: '', // 选课信息数据的ID
        courseId: '', // 此次选课分配的课程的ID
        teacherId: '',// 给此次选课分配的教师的ID
        maxNum: '', // 此次选课分配的课程的课程容量
        week: '', //此次课程在星期几上课
        onClass: '', // 此次课程在第几节课上课(每天共四节课1-4)
        minCredits: '', // 此次选课的课程的学生的最低学分
        maxCredits: '', // 此次选课的课程的学生的最高学分
        grade: '', // 选课的学生的年级的限制
        endTime: '', // 此次选课的课程的结课时间
        stopTime: '' ,// 此次选课的课程的选课截止时间
        isAutoAdd: false //是否自动为符合条件的学生加入课堂

      },
      formLabelWidth: '200px', // 表单标签宽度
    };
  },
  methods: {
    formatStatus(status) {
      const statusMap = {
        '1': '课程进行中',
        '-1': '已结课'
      };
      return statusMap[status] || '未知状态';
    },
    formatSelectStatus(status) {
      const statusMap = {
        '1': '选课进行中',
        '-1': '选课已结束'
      };
      return statusMap[status] || '未知状态';
    },
    convertToISO8601(dateStr) {
      // 解析日期字符串，假设格式为"yyyy/MM/dd"
      const parts = dateStr.split("/");
      const year = parseInt(parts[0], 10);
      const month = parseInt(parts[1], 10) - 1; // 月份是从0开始的
      const day = parseInt(parts[2], 10);

      // 创建一个表示该日期的Date对象，时间默认为00:00:00
      const date = new Date(Date.UTC(year, month, day));

      // 将Date对象转换为ISO 8601格式的字符串
      return date.toISOString();
    },
    prepareNewEntry() {
      this.studentCourseDialogVisible = true;
      this.isEditing = false;
      this.selectCourseForm = { // 编辑学生课程表单的数据模型
          enrollmentId: '', // 选课信息数据的ID
          courseId: '', // 此次选课分配的课程的ID
          teacherId: '',// 给此次选课分配的教师的ID
          maxNum: '', // 此次选课分配的课程的课程容量
          week: '', //此次课程在星期几上课
          onClass: '', // 此次课程在第几节课上课(每天共四节课1-4)
          minCredits: '', // 此次选课的课程的学生的最低学分
          maxCredits: '', // 此次选课的课程的学生的最高学分
          grade: '', // 选课的学生的年级的限制
          endTime: '', // 此次选课的课程的结课时间
          stopTime: '', // 此次选课的课程的选课截止时间
          isAutoAdd: false //是否自动为符合条件的学生加入课堂
      };
    },
    getCourseIdWithName() {
      getCourseIdWithName().then(res => {
        if (res.data.code === 1) {
          this.courseIdWithNameList = res.data.data.list;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    getTeacherIdWithName() {
      getTeacherIdWithName().then(res => {
        if (res.data.code === 1) {
          this.teacherIdWithNameList = res.data.data.list;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    formatClassTime(week, onClass) {
      const weekDays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六','星期日'];
      const classTimes = ['第一节课', '第二节课', '第三节课', '第四节课'];
      return `${weekDays[week - 1]}${classTimes[onClass - 1]}`;
    },
    formatCreditsLimit(min, max) {
      return `${min}~${max}`;
    },
    // 处理编辑选课按钮点击事件
    handleEdit(data) {
      this.isEditing = true;
      this.selectCourseForm = data;
      this.studentCourseDialogVisible = true;
    },
    // 保存课程信息
    saveSelectCourse() {
      this.$refs.selectCourseFormRef.validate((valid) => {
        if (valid) {
          if (this.$common.isEmpty(this.selectCourseForm.minCredits) || this.$common.isEmpty(this.selectCourseForm.maxCredits) || Number(this.selectCourseForm.minCredits) > Number(this.selectCourseForm.maxCredits)){
            this.$message({
              type: 'error',
              message: "学分设置错误"
            });
            return;
          }
          if (this.isEditing) {
            const data = {
              enrollmentId: this.selectCourseForm.enrollmentId,
              courseId: this.selectCourseForm.courseId,
              teacherId: this.selectCourseForm.teacherId,
              maxNum: this.selectCourseForm.maxNum,
              week: this.selectCourseForm.week,
              onClass: this.selectCourseForm.onClass,
              minCredits: this.selectCourseForm.minCredits,
              maxCredits: this.selectCourseForm.maxCredits,
              grade: this.selectCourseForm.grade,
              endTime: this.convertToISO8601(this.selectCourseForm.endTime),
              stopTime: this.convertToISO8601(this.selectCourseForm.stopTime)
            }
            updateSelectCourse(data).then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '编辑成功'
                });
                this.getCoursesList();
                this.studentCourseDialogVisible = false;
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.msg
                });
              }
            })
          } else {
            const data = {
              courseId: this.selectCourseForm.courseId,
              teacherId: this.selectCourseForm.teacherId,
              maxNum: this.selectCourseForm.maxNum,
              week: this.selectCourseForm.week,
              onClass: this.selectCourseForm.onClass,
              minCredits: this.selectCourseForm.minCredits,
              maxCredits: this.selectCourseForm.maxCredits,
              grade: this.selectCourseForm.grade,
              endTime: this.convertToISO8601(this.selectCourseForm.endTime),
              stopTime: this.convertToISO8601(this.selectCourseForm.stopTime),
              isAutoAdd: this.selectCourseForm.isAutoAdd ? 1 : 0 //是否自动为符合条件的学生加入课堂
            }
            addSelectCourse(data).then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '新增成功'
                });
                this.getCoursesList();
                this.studentCourseDialogVisible = false;
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.msg
                });
              }
            })
          }
        } else {
          // 校验未通过
          this.$message.error('表单中有错误，请修正后再提交');
          return false;
        }
      });
    },

    // 前端排序函数
    handleSortChange({prop, order}) {
      if (!order) {
        // 如果没有排序顺序，可能是恢复到未排序状态
        this.getCoursesList();
        return;
      }

      // 根据排序信息对 articleList 进行排序
      // articleList 是一个数组，包含要显示在表格中的文章
      this.enrollmentList.sort((a, b) => {
        if (order === 'ascending') {
          return a[prop] - b[prop]; // 升序排序
        } else {
          return b[prop] - a[prop]; // 降序排序
        }
      });
    },
    // 处理搜索显示/隐藏的逻辑
    handleToggleSearch() {
      this.showSearch = !this.showSearch;
    },
    // 处理刷新数据的逻辑
    handleRefresh() {
      this.getCoursesList();
      this.$message.success('列表已刷新');
    },
    // 搜索选课的方法
    handleQuery() {
      this.loading = true;
      // 重置当前页为第一页
      this.pagInfo.currentPage = 1;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = {
        name: this.queryParams.name,
        teacherName: this.queryParams.teacherName,
      }
      const DTOdata = {
        pagination,
        queryParams//只有搜索时才会带上
      }
      getEnrollment(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((enrollment) => {
            enrollment.endTime = this.$common.dateFormat(enrollment.endTime);
            enrollment.stopTime = this.$common.dateFormat(enrollment.stopTime);
          });
          this.enrollmentList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    // 处理表格行选择事件
    handleSelectionChange(selection) {
      this.enrollmentIdList = selection.map(item => item.enrollmentId);
    },
    //批量结课方法
    handleBatchEndEnrollment() {
      if (this.enrollmentIdList.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择要结束的课堂'
        });
        return;
      }
      // 确认弹窗
      this.$confirm('确定要结束选中的课堂吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          ids: this.enrollmentIdList
        }
        endEnrollmentOnList(data).then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '结束成功'
            });
            this.getCoursesList();
          } else {
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消结束课程'
        });
      });
    },
    // 教务人员结课方法
    handleEndCourse(id) {
      if (id) {
        this.$confirm('确定要结束该课堂吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const data = {
            enrollmentId: id
          }
          // 这里应该是一个API请求，删除文章
          adminEndCurse(data).then(res => {
            if (res.data.code === 1) {
              this.$message({
                type: 'success',
                message: '课堂结束成功'
              });
              this.getCoursesList();
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '已取消结束课堂'
          });
        });
      }
    },
    // 教务人员结束选课方法
    handleStopSelectCourse(id) {
      if (id) {
        this.$confirm('确定要结束该选课吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const data = {
            enrollmentId: id
          }
          adminStopSelectCourse(data).then(res => {
            if (res.data.code === 1) {
              this.$message({
                type: 'success',
                message: '结束选课成功'
              });
              this.getCoursesList();
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '已取消结课'
          });
        });
      }
    },
    // 获取课程列表的方法
    async getCoursesList() {
      this.loading = true;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = null;
      const DTOdata = {
        pagination,
        queryParams
      }
      await getEnrollment(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((enrollment) => {
            enrollment.endTime = this.$common.dateFormat(enrollment.endTime);
            enrollment.stopTime = this.$common.dateFormat(enrollment.stopTime);
          });
          this.enrollmentList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    }
  },
  created() {
    this.getCoursesList();
    this.getCourseIdWithName();
    this.getTeacherIdWithName();
  }
};
</script>

<style scoped>

.scroll-container {
  max-height: 646px; /* 您可以根据需要调整这个值 */
  overflow-y: auto;
}

.sdf {
  background: transparent;
  border-color: transparent;
  color: #76d7ff;
}

.sd {
  background: transparent;
  border-color: transparent;
  color: #fa1224;
}

.image-cover {
  width: 100px;
  height: 60px;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;

  .image-slot {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    color: #909399;
  }
}

.time {
  display: flex;
  align-items: center;
}
</style>

